<template>
    <w-tab-list  @clear-search="clearSearch(true)"
                 @clear-selection="clearSelection"
                 @refresh-data="refreshData(true)"
                 @switch-page="switchPage"
                 @search-active="searchActive"
                 @delete-batch="remove"
                 @open-add-from="insert"
                 :total="paging.total"
                 :page-size="paging.pageSize"
                 :frame="false"
    >
        <template #searchItem>
            <ul style="float:left;">
                <li>
                    角色名称：<el-input type="text" placeholder="请输入角色名称" class="sh" v-model="search.nameCh"/>
                </li>
                <li>
                    角色编码：<el-input type="text" placeholder="请输入角色编码" class="sh" v-model="search.name"/>
                </li>
                <li>
                    状态：<el-select v-model="search.status" placeholder="选择状态" clearable>
                            <el-option label="启用" :value="1"/>
                            <el-option label="未启用" :value="0"/>
                        </el-select>
                </li>
                <li>
                    创建时间：<el-date-picker v-model="search.date" type="daterange" size="default" start-placeholder="开始时间" end-placeholder="结束时间" clearable class="picker"/>
                </li>
            </ul>
        </template>
        <template #batchOperationItem>
<!--            <div class="displayColumn">-->
                <el-checkbox label="显示备注" v-model="display.remark" class="display-column"/>
<!--            </div>-->
        </template>
        <template #dataList>
            <el-table stripe :data="roleData"
                      @selection-change="saveSelection"
                      header-row-class-name="header-class"
                      v-loading="loading"
                      element-loading-text="正在加载角色数据"
                      ref="roleTable" class="table">
                <el-table-column type="selection" width="55" :selectable="selectTable"/>
                <el-table-column prop="id" label="角色编号" width="90" align="center"/>
                <el-table-column prop="roleNameCh" label="角色名称"/>
                <el-table-column prop="roleName" label="角色编码"/>
                <el-table-column prop="sort" label="显示顺序" width="80" align="center"/>
                <el-table-column prop="remark" label="备注" show-overflow-tooltip v-if="display.remark" width="200"/>
                <el-table-column label="状态">
                    <template #default="scope">
                        <el-switch v-model="scope.row.enabled"
                                   :active-value="1"
                                   :inactive-value="0"
                                   active-text="正常"
                                   inactive-text="停用"
                                   :before-change="switchEnabled"
                                   @change="enableChange($event,scope.row)"
                                   active-color="#13ce66"
                                   inactive-color="#ff4949"
                                   size="small"
                                   :disabled="scope.row.id===1"
                        />
                    </template>
                </el-table-column>
                <el-table-column prop="createTime" label="创建时间"/>
                <el-table-column label="操作" width="200">
                    <template #default="s">
                        <el-button type="text" size="small" @click="edit(s.row)" :icon="Edit" :disabled="s.row.id===1">编辑</el-button>
                        <el-button type="text" size="small" @click="remove(s.row)" :icon="Delete" :disabled="s.row.id===1">删除</el-button>
                        <el-button type="text" size="small" :icon="SetUp" @click="editPermissionMenuClick(s.row)" v-if="s.row.id!==1">设置权限</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </template>
    </w-tab-list>
    <role-form width="43.8%" ref="roleForm" @refresh-data="refreshData"/>
    <role-permission-form ref="rolePermissionFormRef" @refresh-data="refreshData"/>
</template>

<script>
    import {Search,Refresh,RefreshRight,CollectionTag,Delete,Plus,Edit,DArrowRight,Picture,Failed,Menu,SetUp} from '@element-plus/icons-vue'
    import {ElLoading,ElMessage} from 'element-plus'
    import RoleForm from "./form/RoleForm.vue";
    import WTabList from "../../com/WTabList.vue";
    import {deleteRole, getRolesPageInfo, updateRole} from "../../../network/sys/role";
    import RolePermissionForm from "./form/RolePermissionForm.vue";

    export default {
        name: "RoleMain",
        components:{
            RolePermissionForm,
            RoleForm,
            WTabList
        },
        setup(props){
            return{
                Search,
                Refresh,
                RefreshRight,
                CollectionTag,
                Delete,
                Plus,
                Edit,
                DArrowRight,
                Picture,
                Failed,
                Menu,
                SetUp
            }
        },
        data(){
            return{
                roleData: [],
                selection: [],
                paging:{
                    total: 0,//记录总数
                    pageSize: 9,//每页记录数
                    pageNum: 1,//当前页码
                    pagerCount: 8,//最大页码按钮数，限定在(5 ≤ x ≤ 21 的奇数)
                },
                search:{
                    name: null,
                    nameCh: null,
                    status: null,
                    date: null,
                },
                loading:{
                    value:false
                },
                display: {
                    remark: false
                }
            }
        },
        methods:{
            editPermissionMenuClick(row){
                let frm = this.$refs.rolePermissionFormRef;
                frm.setRole(row);
                frm.visible = true;
            },
            selectTable(row,index){
                return row.id !== 1;
            },
            /*1、搜索框管理*/
            //搜索执行函数
            searchActive(){
                this.$utils.searchActive({
                    data: this.search,
                    initData: this.$options.data.call(this).search,
                    executeFn:()=>{
                        this.loadRolesPageInfoReq();
                    }
                })
            },
            //清空搜索框
            clearSearch(hint){
                this.$utils.resetSearchParams({
                    initData: this.$options.data.call(this).search,
                    data: this.search,
                    hint: hint,
                    callback: ()=>{
                        this.loadRolesPageInfoReq();
                    }
                });
            },
            //删除元素
            remove(row){
                let a = this.$refs.roleTable.getSelectionRows();
                if(row){
                    this.$operate.remove({
                        title: `删除角色`,
                        data: `' ${row.roleNameCh} '`,
                        executeFn: ()=>{
                            let ids = [row.id]
                            this.deleteExecute(ids);
                        }
                    })
                }else{
                    this.$operate.removeBatch({
                        title: `删除选中的角色`,
                        selection: this.selection,
                        key: 'id',
                        executeFn: (ids)=>{
                            this.deleteExecute(ids);
                        }
                    })
                }
            },
            deleteExecute(ids){
                deleteRole(ids).then(vo=>{
                    this.$response.handle({
                        data: vo,
                        success: '删除成功',
                        error: '删除失败',
                        successFn: ()=>{
                            this.refreshData();
                        }
                    })
                })
            },
            //修改角色状态
            switchEnabled(){
                return this.$operate.switchStatus({
                    title: '修改角色状态',
                    hint: '你确认要更改该角色状态吗'
                });
            },
            //修改角色状态执行
            async enableChange($event,row){
                // console.log('val',$event);
                // console.log('id',row.id)
                // console.log('row',row)
                let loading = ElLoading.service({
                    target: '.table',
                    text: '正在修改'
                })
                await updateRole({
                    id: row.id,
                    enabled: $event
                }).then(data=>{
                    loading.close();
                   this.$response.handle({
                       data:data,
                       success: '修改成功',
                       error: '修改失败',
                       failFn:()=>{
                           row.enabled = ($event === 0 ? 1 : 0);
                       }
                   })
                })
            },
            /*3.分页管理*/
            //切换页面
            async switchPage(index){
                this.paging.pageNum = index;
                await this.loadRolesPageInfoReq();
            },
            /*4.对话框管理*/
            //打开新增对话框
            insert(){
                let frm = this.$refs.roleForm;
                frm.visible = true;
                frm.type = 0;
                frm.title = '添加角色信息';
                // frm.$refs.formRef.value.clearValidate();
            },
            //编辑记录
            edit(row){
                let frm = this.$refs.roleForm;
                frm.type = 1;
                frm.title = '修改角色信息';
                frm.visible = true;
                this.$nextTick(function (){
                    frm.setRole(row);
                })
            },
            /*5.表格管理*/
            //刷新表格数据
            refreshData(hint){
                this.loadRolesPageInfoReq(hint);
            },
            //保存用户选中行数据
            saveSelection(selection){
                this.selection = selection;
            },
            clearSelection(){
                this.$refs.roleTable.clearSelection();
            },
            /*6.数据加载项*/
            loadRolesPageInfoReq(hint){
                let params = {
                    roleName: this.search.name,
                    roleNameCh: this.search.nameCh,
                    enabled: this.search.status,
                    start: this.search.date==null ? null : new Date(this.search.date[0]).format('yyyy-MM-dd'),
                    end: this.search.date==null ? null : new Date(this.search.date[1]).format('yyyy-MM-dd'),
                    pageNum: this.paging.pageNum,
                    pageSize: this.paging.pageSize
                }
                this.loading = true;
                getRolesPageInfo(params).then(vo=>{
                    this.loading = false;
                    this.$response.loadPageInfo({
                        data: vo,
                        executeFn: ()=>{
                            this.roleData = vo.list;
                            this.paging.total = vo.total;
                        },
                        hint: hint,
                        log: '角色列表数据'
                    })
                })
            },
            init(){
                this.loadRolesPageInfoReq();
            }
        },
        created() {
            this.init();
        }
    }
</script>

<style scoped>
    .tab-list{
        height: 99%;
    }
    .sh{
        width: 180px;
    }
    .el-select-dropdown__item{
        width: 100%;
        color: darkgray;
    }
    .el-select{
        width: 120px;
    }
    .display-column{
        padding: 0 20px;
        position: relative;
        top: 4px;
    }
</style>